﻿using FlowerShop.Core.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.Services
{
    public class OrderService
    {
        private readonly Model1 _context = new Model1();

        // 创建新订单
        public void CreateOrder(int userId, string userName, string address, List<Tshoppingcars> cartItems, decimal totalPrice)
        {
            userName = string.IsNullOrEmpty(userName) ? "匿名用户" : userName;

            var order = new Torder
            {
                O_name = userName,
                O_date = DateTime.Now,
                O_add = address,
                City = address.Split(',')[1].Trim(),
                State = address.Split(',')[2].Trim(),
                youbian = address.Split(',')[3].Trim(),
                phone = address.Split(',')[4].Trim(),
                O_zhuangtai = "未审核",
                O_profit = totalPrice,
                W_id = userId,
                O_qianshou = "未付款",
                O_pinglun = "正常",
                O_dafen = "未分配",
                O_huaduoming = string.Join(",", cartItems.Select(ci => ci.G_id.ToString()))
            };

            _context.Torder.Add(order);
            _context.SaveChanges();


        }
        // 审核订单
        public List<Torder> GetOrders(int userId)
        {
            // 如果 userId 是 0 或者其他，返回所有订单
            return userId == 0
                ? _context.Torder.ToList()
                : _context.Torder.Where(o => o.W_id == userId).ToList();
        }

        public void ApproveOrder(int orderId)
        {
            var order = _context.Torder.FirstOrDefault(o => o.O_id == orderId);
            if (order != null)
            {
                order.O_zhuangtai = "已审核";
                _context.SaveChanges();
            }
        }

        // 获取员工业绩信息
        public List<EmployeePerformance> GetEmployeePerformance()
        {
            var performanceList = _context.Torder
                .Where(o => o.O_zhuangtai == "已审核")
                .GroupBy(o => o.W_id)
                .Select(g => new EmployeePerformance
                {
                    EmployeeName = g.FirstOrDefault().Twoker.t_name,
                    OrderCount = g.Count(),
                    TotalProfit = g.Sum(o => o.O_profit ?? 0)
                })
                .ToList();

            return performanceList;
        }
    }
}
